package de.hszg.wjl.datacore.model;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import static org.junit.Assert.*;

public abstract class QuestionTest<T extends AbstractQuestion> {

	abstract protected String getQuestionXML();

	@SuppressWarnings("unchecked")
	protected T createQuestion() {
		Node node = getNode(getQuestionXML());
		T question = null;
		try {
		question = (T) createQuestion(node);
		} catch (Exception e) {
			fail("Incorrect Question type.");
		}
		question.setFields(node);
		return question;
	}

	private Node getNode(String xml) {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

			doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
		} catch (Exception e) {
		}
		return doc.getDocumentElement();

	}

	private AbstractQuestion createQuestion(Node xml) {
		Node namedItem = xml.getAttributes().getNamedItem("type");
		String type = namedItem.getNodeValue();
		try {
			AbstractQuestion question = QuestionType
					.getAbstractQuestionInstance(type);
			question.setFields(xml);
			return question;
		} catch (Exception e) {
			fail(e.getMessage());
			return null;
		}

	}

}
